package deptlogic

import (
	"context"

	"go-zero-admin/apps/system/cmd/rpc/internal/svc"
	"go-zero-admin/apps/system/cmd/rpc/syspb"
	"go-zero-admin/apps/system/model"
	"go-zero-admin/pkg/constant"
	"go-zero-admin/pkg/tool"
	"go-zero-admin/pkg/xerr"

	"github.com/duke-git/lancet/v2/convertor"
	"github.com/duke-git/lancet/v2/validator"
	"github.com/jinzhu/copier"
	"github.com/pkg/errors"
	"github.com/zeromicro/go-zero/core/logx"
)

type AddDeptLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
	isExDeptNameLogic *IsExDeptNameLogic
}

func NewAddDeptLogic(ctx context.Context, svcCtx *svc.ServiceContext) *AddDeptLogic {
	return &AddDeptLogic{
		ctx:               ctx,
		svcCtx:            svcCtx,
		Logger:            logx.WithContext(ctx),
		isExDeptNameLogic: NewIsExDeptNameLogic(ctx, svcCtx),
	}
}

func (l *AddDeptLogic) AddDept(in *syspb.AddDeptReq) (*syspb.AddDeptResp, error) {
	dept := in.GetParams()
	if dept == nil || dept.GetDeptName() == "" || dept.GetCreateUser() == "" || dept.GetUpdateUser() == "" {
		return nil, errors.Wrapf(xerr.NewErrMsg("新增部门失败：参数缺失"),
			tool.GetErrMsgFormat("insert dept"), "params is not existed", in)
	}
	if dept.GetPhone() != "" && !validator.IsChineseMobile(dept.GetPhone()) {
		return nil, errors.Wrapf(xerr.NewErrMsg("手机号数据错误"),
			tool.GetErrMsgFormat("insert dept"), "phone params error", in)
	}
	if dept.GetEmail() != "" && !validator.IsEmail(dept.GetEmail()) {
		return nil, errors.Wrapf(xerr.NewErrMsg("邮箱数据错误"),
			tool.GetErrMsgFormat("insert dept"), "email params error", in)
	}

	// 判断用户同部门下是否有相同的名称
	isExist, err := l.isExDeptNameLogic.IsExDeptName(&syspb.IsExDeptNameReq{
		DeptName: dept.GetDeptName(),
		ParentId: dept.GetParentId(),
	})
	if err != nil {
		return nil, err
	}
	if isExist.GetIsExist() {
		return nil, errors.Wrapf(xerr.NewErrMsg("新增部门："+dept.GetDeptName()+" 失败，部门名称已存在"),
			tool.GetErrMsgFormat("insert dept"), "dept name is existed", in)
	}

	// 如果父节点不为正常状态，则不允许新增子节点
	// 因无需判断错误，可不处理错误
	parentDept, _ := l.svcCtx.SysDeptModel.FindOne(l.ctx, dept.GetParentId())
	if parentDept != nil && parentDept.Status == constant.DeptStatusOff {
		return nil, errors.Wrapf(xerr.NewErrMsg("新增部门："+dept.GetDeptName()+" 失败，部门停用不允许新增"),
			tool.GetErrMsgFormat("insert dept"), "dept is stoped", in)
	}

	// 设置默认值
	if parentDept != nil {
		dept.Ancestors = parentDept.Ancestors + "," + convertor.ToString(dept.GetParentId())
	} else {
		dept.Ancestors = "0"
	}

	// 转换数据
	var data model.SysDept
	_ = copier.Copy(&data, in.GetParams())

	// 保存数据
	_, err = l.svcCtx.SysDeptModel.InsertEx(l.ctx, nil, []*model.SysDept{&data})
	if err != nil {
		return nil, errors.Wrapf(xerr.NewErrCode(xerr.DbError), tool.GetErrMsgFormat("insert dept"), err, in)
	}

	return &syspb.AddDeptResp{}, nil
}
